package com.yundasys.lab08jvm.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jiangta
 * @version 1.0
 * @date 2021/6/30 4:12 下午
 */
class ShareResource {
    private volatile int number = 1;
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void print5() throws InterruptedException {
        lock.lock();
        try {
            while (number != 1) {
                condition1.await();
            }
            number = 2;
            condition2.signal();

            for (int i = 0; i < 5; i++) {
                System.out.println("AA");
            }
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
    }

    public void print10() throws InterruptedException {
        lock.lock();
        try {
            while (number != 2) {
                condition2.await();
            }
            number = 3;
            condition3.signal();

            for (int i = 0; i < 10; i++) {
                System.out.println("BB");
            }
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
    }

    public void print15() throws InterruptedException {
        lock.lock();
        try {
            while (number != 3) {
                condition3.await();
            }
            number = 1;
            condition1.signal();

            for (int i = 0; i < 15; i++) {
                System.out.println("CC");
            }
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
    }
}

public class SyncAndReentrantLockDemo {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareResource.print5();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "AA").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareResource.print10();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "BB").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareResource.print15();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "CC").start();
    }
}
